<script setup lang="ts">
import {ref,watch,} from 'vue'
import type{FormInstance} from 'ant-design-vue'
import {message} from 'ant-design-vue'
import useRequestList from './requestList'

const emits = defineEmits(['close'])
const props = withDefaults(defineProps<{
	visible: boolean
	title:string
  editRequest:{[key:string]:any}
	pageList?:{[key:string]:any}[]
}>(),{
  pageList:()=>([]),
})


const requestList=useRequestList()
const needAuthPage=ref(true)
const isSuccessOperate=ref(false)

const formLayout = {
	style: 'margin: 0 10px',
	labelCol: { span: 6 },
	wrapperCol: { span: 18 },
	labelAlign: 'left',
}
const rowFormItemLayout = {
	labelCol: { span: 3 },
	wrapperCol: { span: 21 },
}
const rules = ref({
	requestName: [
		{ required: true, message: '请输入请求名！', trigger: 'change' },
		{ pattern: /^[a-zA-Z]+$/, message: '请求名只能包含英文！', trigger: 'change' },
	],
	requestPath: [{ required: true, message: '请输入请求路径！', trigger: 'change' }],
	needAuth: [{ required: true, message: '请选择是否需要授权访问！', trigger: 'change' }],
	description: [{ required: true, message: '请输入接口描述！', trigger: 'change' }],
	routeKeys: [{ required: true, message: '请输选择接口所在的页面！', trigger: 'change' }],
})

type dataType={
	requestName: string
	requestPath: string
	needAuth: 0|1
	description:string
	routeKeys:any[]
	[key:string]:any
}

const initFormData: dataType = {
	requestName: '',
	requestPath: '',
	needAuth: 1,
	description: '',
	routeKeys:[],
}
const formData = ref<dataType>({ ...initFormData })

const formInstance = ref<FormInstance | null>(null)

function showBack(){
	formInstance.value?.resetFields()
  Object.keys(initFormData).forEach(k=>{
    if(k!='routeKeys')
    formData.value[k]=props.editRequest[k]
  })

	if(props.editRequest.routeIds)
  formData.value.routeKeys=props.editRequest.routeIds.split(',')
  
	handleAuthChange(formData.value.needAuth?1:0)

}

function handleAuthChange(v:0|1){
   if(!v)  {
		rules.value.routeKeys[0].required=false
    needAuthPage.value=false
	 }else{
		rules.value.routeKeys[0].required=true
    needAuthPage.value=true
	 } 
}

async function handleOk() {
	try {
		await formInstance.value?.validate()
		// console.log(values)
    let routeIds='',routeNames='',routeTitles=''
		if(formData.value.routeKeys.length)
		props.pageList.forEach(v=>{
			if(formData.value.routeKeys.includes(v.id)){
				  if(!routeIds) routeIds=v.id
          else routeIds+=","+v.id
				  if(!routeNames) routeNames=v.name
          else routeNames+=","+v.name
				  if(!routeTitles) routeTitles=v.title
          else routeTitles+=","+v.title
			}
    })
		let params:requestItem={...props.editRequest,...formData.value,routeIds,routeNames,routeTitles,id:props.editRequest.id}
		delete params.routeKeys
		const res=await requestList.updateItem(params)
		if (res.code == 200) {
			isSuccessOperate.value = true
			emits('close', isSuccessOperate.value)
		}
		else if (res.code == 201)
			message.error('请求名已存在！')
		}catch(error){
        console.log(error)
		}
		
}

watch(
	() => props.visible,
	(nv) => {
		if (nv) {
			isSuccessOperate.value = false
			showBack()
		}
	}
)
</script>

<template>
	<a-modal :visible="visible" :title="title" :maskClosable="false" width="68%"  :mask="false" @ok="handleOk" @cancel="emits('close')">
		<a-form :model="formData" :rules="rules" v-bind="formLayout" ref="formInstance">
			<a-row :gutter="[24, 8]">
				<a-col :span="24">
					<a-form-item name="requestName" label="请求名" v-bind="rowFormItemLayout">
						<a-input
							v-model:value="formData.requestName"
							placeholder="请求名必须唯一，也用作请求的权限值。"
							allowClear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="24">
					<a-form-item name="needAuth" label="是否需要授权访问" v-bind="rowFormItemLayout">
						<a-select v-model:value="formData.needAuth" placeholder="无需授权的话，则该接口任意角色可访问" @change="handleAuthChange" allowClear>
							<a-select-option :value="1">是</a-select-option>
							<a-select-option :value="0">否</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="24">
					<a-form-item name="requestPath" label="请求路径" v-bind="rowFormItemLayout">
						<a-input v-model:value="formData.requestPath" placeholder="请输入接口的请求路径" allowClear />
					</a-form-item>
				</a-col>
				<a-col :span="24">
					<a-form-item name="description" label="接口描述" v-bind="rowFormItemLayout">
						<a-input v-model:value="formData.description" placeholder="请输入接口描述" allowClear />
					</a-form-item>
				</a-col>
				<a-col :span="24" v-show="needAuthPage">
					<a-form-item name="routeKeys" label="所在的页面集合" v-bind="rowFormItemLayout"  > 
            <a-select mode="multiple" v-model:value="formData.routeKeys" placeholder="请选择该接口会出现在哪些页面" :options="pageList" optionFilterProp="label"  allowClear />
          </a-form-item>
				</a-col>
			</a-row>
		</a-form>
	</a-modal>
</template>

<style scoped>

</style>
